<script setup lang="ts">
import { getContentDataByIdApi, getDatasetInstructionByIdApi, getDatasetPdfByIdApi, getPublishDataByIdApi } from '@/api/data/datasetDetails';
import { getIcon } from '@/api/assets/assets';
import { computed, onMounted, ref } from 'vue';
import type { DataInfoCard, Dataset, ReleaseInfoCard } from '@/api/data/types/dataInfoCard';
import Header from './DetailPageHeader.vue';
import InfoCard from './DetailPageInfoCard.vue';

const props = defineProps({
  datasetid: {
    type: String,
    required: true,
  },
});

const imageUsrName = ref<string | null>(null);
const imageDownloadNum = ref<string | null>(null);

const fetchIcon = async () => {
  try {
    const data = await getIcon(['yhtx_dlzc_head2.png', '31.png']);
    imageUsrName.value = data['yhtx_dlzc_head2.png'];
    imageDownloadNum.value = data['31.png'];
  }
  catch (error) {
    console.error('API 调用错误:', error);
  }
};

// 本地存储中的 app 数据（包含 datasetId 和其他相关信息）
const storedApp = ref<Dataset | null>(null);

// 状态数据
const releaseInfoData = ref<ReleaseInfoCard | null>(null);
const infoCardData = ref<DataInfoCard | null>(null);
const pdfUrl = ref<string | null>(null);

// 组件挂载时获取数据
onMounted(() => {
  fetchIcon();
  const fetchData = async () => {
    try {
      // 获取数据集基本元信息
      const tmpDateset: any = await getContentDataByIdApi(props.datasetid)

      storedApp.value = {
        datasetId: tmpDateset.datasetId,
        title: tmpDateset.name,
        description: tmpDateset.description,
        date: tmpDateset.createdTime,
        views: tmpDateset.clickNum ? tmpDateset.clickNum.toString() : '0',
        likes: tmpDateset.favoriteNum ? tmpDateset.favoriteNum.toString() : '0',
        comments: 0, // 如果有评论数据，请替换此处
        downloads: tmpDateset.downloadNum ? tmpDateset.downloadNum.toString() : '0',
        shares: tmpDateset.shareNum ? tmpDateset.shareNum.toString() : '0',
        username: tmpDateset.creatorName,
        favorites: tmpDateset.favoriteNum ? tmpDateset.favoriteNum.toString() : '0',
        tags: tmpDateset.tags || [],
        image: tmpDateset.imagePath,
        link: tmpDateset.url,
      }

      // 请求发布信息数据
      const publishResponse = await getPublishDataByIdApi(props.datasetid)
      const data = publishResponse;
      releaseInfoData.value = {
        organization: data.publishAgency || '未知机构',
        releaseDate: data.publishTime || '未知时间',
        releaseHomepage: data.publishHomepage || '未知首页',
        releaseLink: data.publishHomepage || '未知链接',
      };

      // 请求数据集简介数据
      const introResponse = await getDatasetInstructionByIdApi(props.datasetid)
      if (introResponse) {
        const data = introResponse;
        infoCardData.value = {
          title: storedApp.value.title || '未知标题',
          description: data.introduce || '无描述',
          citationTitle: '引文',
          citation: data.citation || '无引文',
          datasetInfoTitle: '数据集信息',
          datasetInfo: data.dataInformation || '无数据集信息',
          acknowledgmentTitle: '致谢',
          acknowledgment: data.acknowledgements || '无致谢',
        };
      }
      // 请求 PDF 的 URL
      const pdfResponse = await getDatasetPdfByIdApi(props.datasetid);
      if (pdfResponse)
        pdfUrl.value = pdfResponse.data;
        // console.log('PDF URL received:', pdfResponse.data);

      else
        pdfUrl.value = null;
        // console.error('No PDF URL received from backend:', pdfResponse.data);
    }
    catch (error) {
      pdfUrl.value = null;
      console.error('Error fetching data:', error);
    }
  };

  fetchData();
});

// 处理 newCardData 的数据
const metaData = computed(() => ({
  title: storedApp.value?.title || '无标题',
  description: storedApp.value?.description || '无描述',
  date: storedApp.value?.date || '无日期',
  views: storedApp.value?.views || '无浏览量',
  likes: storedApp.value?.likes || '无点赞数',
  comments: storedApp.value?.comments || 0,
  downloads: storedApp.value?.downloads || '无下载数',
  shares: storedApp.value?.shares || '无分享数',
  username: storedApp.value?.username || '未知用户',
  favorites: storedApp.value?.favorites || '无收藏数',
  tags: storedApp.value?.tags || [],
  size: storedApp.value?.downloads || '未知大小',
  image: storedApp.value?.image || '',
  link: storedApp.value?.link || '',
}));
</script>

<template>
  <div class="data-content">
    <!-- 展示 MetaData 组件 -->
    <Header :data="metaData" />

    <!-- 加载信息卡片或加载中提示 -->
    <InfoCard
      v-if="infoCardData || releaseInfoData || pdfUrl" :data="infoCardData || {}"
      :release-info="releaseInfoData || {}" :pdf-url="pdfUrl"
    />
  </div>
</template>

<style scoped>
/* 样式自定义 */
.data-content {
  margin-left:0.5rem;
  margin-right:0.5rem;
}
</style>
